#include "GraphVisualisation.h"
#include "A-Star.h"
#include <Clarity/Rendering/SceneManager.h>
#include <Clarity/Rendering/SceneNode.h>
#include <Clarity/Renderable/Sprite.h>
#include <Clarity/Renderable/RenderableLineSegment.h>
#include <Clarity/Math/LineSegment2.h>
#include <map>

GraphVisualisation::GraphVisualisation(AStar *s_AStar, SceneManager *sceneManager)
   : m_AStar(s_AStar), m_sceneManager(sceneManager)
{
   if (!m_sceneManager)
   {
      return;
   }

   int nodeCount = m_AStar->NodeCount();

   for (int i = 0; i < nodeCount; i++)
   {
      CreateNodeVisualisation(m_AStar->GetNode(i));
	  CreateEdgeVisualisation(m_AStar->GetNode(i));
   }

   //int edgeCount = graph->EdgeCount();

   //std::multimap<GraphNode *, GraphNode *> nodeMap;

   //for (int i = 0; i < edgeCount; i++)
   //{
   //   GraphEdge *edge = graph->GetEdge(i);

   //   // Only draw edges in one direction
   //   bool found = false;

   //   pair<multimap<GraphNode *, GraphNode *>::iterator, multimap<GraphNode *, GraphNode *>::iterator> ii;
   //   multimap<GraphNode *, GraphNode *>::iterator it;

   //   ii = nodeMap.equal_range(edge->GetNode(1));

   //   for (it = ii.first; it != ii.second; ++it) 
   //   {
   //      if (it->second == edge->GetNode(0))
   //      {
   //         found = true;
   //         break;
   //      }
   //   }

   //   if (!found)
   //   {
   //      nodeMap.insert(make_pair(edge->GetNode(0), edge->GetNode(1)));
   //      CreateEdgeVisualisation(edge);
   //   }
   //}
}

void GraphVisualisation::CreateNodeVisualisation(ANode *node)
{
   SharedPtr<SceneNode> sceneNode(m_sceneManager->GetRoot()->CreateChild());
   SharedPtr<ISprite> sprite(SpriteCreate("MazeBot", "data/shapes/Circle16.tga", true, 2000, 16, 16, 1, m_sceneManager->GetRenderSystem()));
   sceneNode->AttachObject(sprite->GetSceneObject());
   sceneNode->SetPosition2D(node->m_Pos);
   m_sceneNode.push_back(sceneNode);
   m_sprite.push_back(sprite);
}

void GraphVisualisation::CreateEdgeVisualisation(ANode *s_Node)
{
	//Get Number of Nodes this node is connected to
	//iterate through all of them and create a line from s_Node to each on the NodeList
	int numEdge = s_Node->m_NodeList.size();

	for(int i = 0; i < numEdge; ++i)
	{
		LineSegment2 lineSegment(s_Node->m_Pos, s_Node->m_NodeList[i]->m_Pos);
		SharedPtr<RenderableLineSegment> rend(new RenderableLineSegment(m_sceneManager->GetRenderSystem(), lineSegment));
		m_sceneManager->GetRoot()->AttachObject(rend.Get());
		m_line.push_back(rend);
	}
}